<?php

$totalCount = 0;
class importTwoTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
    // $this->addArguments(array(
    //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
    // ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, '', 'frontend'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
      new sfCommandOption('file', null, sfCommandOption::PARAMETER_REQUIRED, 'LUA File to convert', 'data/RPBot.lua'),
      // add your own options here
    ));

    $this->namespace        = 'raidpoints';
    $this->name             = 'importTwo';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [import|INFO] task does things.
Call it with:

  [php symfony import|INFO]
EOF;
  }

  public function doLogSection($section, $message, $size = NULL, $style ='INFO')
  {
      global $totalCount;

      $q = Doctrine::getTable("DataImportStatus")
          ->createQuery()
          ->orderBy("date desc")
          ->limit(1);
      $r = $q->execute();

      $is = new DataImportStatus();
      $is->setDate(gmdate("Y-m-d H:i:s", time()));
      $is->setStatus($section);
      $is->setText($message);
      $is->setStatustotal($totalCount);
      if (isset($size))
      {
          $is->setStatusbar(0);
          $size = null;
      }
      elseif ($r->count() == 1)
      {
          $is->setStatusbar($r->getFirst()->getStatusbar()+1);
      }
      else
      {
          $is->setStatusbar(0);
      }
      $is->save();
      $this->logsection($section, $message, $size, $style);
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
    // add your code here
    //

    global $totalCount;
    $logT = "\t".date("F d, Y, g:i:s a", time());

    $this->doLogSection("Working", $logT, 0);
    $this->doLogSection("Working", "Opening Saved Variables file...");
    $this->doLogSection("Working", $options["file"]);

    $lua = new LuaConverter();
    //copy($options["file"], "web/upload/".date("m.d.y H-i-s").".lua");
    $raiddata = ($lua->convert(utf8_decode(file_get_contents($options["file"]))));

    $this->doLogSection("Working", "Loading Saved Variables...");

    eval($raiddata);

    if (isset($rpDEBUGBotDB))
    {
        $arrayi = $rpDEBUGBotDB;
    }
    else
    {
        $arrayi = $rpBotDB;
    }

    $sortedraid = $arrayi["realm"];

    $this->doLogSection("Working", "Itterating Saved Variables...");
    foreach ( $sortedraid as $realm => $rdata )
    {
        foreach ( $rdata["player"] as $player => $pdata )
        {
            $query = Doctrine::getTable("Player")
                ->createQuery()
                ->where("name=?", strtolower(utf8_encode($pdata["name"])));
            $result = $query->execute();
//                if ($result->count() == 0)
//                {
//                    $p = new Player();
//                    $p->setFullname(utf8_encode($pdata["fullname"]));
//                    $p->setName(utf8_encode($pdata["name"]));
//                    $p->setAltid(1);
//                    $p->setGuildedflag(1);
//
//                    $query = Doctrine::getTable("PClass")
//                        ->createQuery()
//                        ->where("LOWER(name)=?", strtolower($pdata["class"]));
//                    $result = $query->execute();
//                    $c = $result->getFirst();
//                    $p->setPClass($c);
//                    //print_r($p->toArray());
//                    try
//                    {
//                        $p->trySave();
//                        $this->doLogSection("Working", "New Player: ".$p->getFullname());
//                        $rdata["player"][$player]["id"] = $p->getId();
//                    }
//                    catch (exception $ex)
//                    {
//
//                    }
//                }
        }
        global $totalCount;
        $totalCount = 0;

        $playerList = array();
        $query = Doctrine::getTable("Player")->getPlayerList()->select('id, name');
        $result = $query->execute();
        foreach ($result as $r)
        {
            $playerList[($r['name'])] = $r['id'];
        }

        foreach ( $rdata["raid"] as $raid => $value )
        {
            $recentactionsByPlayer = array();
            $raMisc = array();
            $query = Doctrine::getTable("Raid")
                ->createQuery()
                ->where("short=?", $raid)
                ->andWhere("server=?", $realm);
            $result = $query->execute();
            $r = null;
            if ($result->count() > 0)
                $r = $result->getFirst();
            else
            {
                $r = new Raid();
                $r->setName($raid);
                $r->setShort($raid);
                $r->setVisible(0);
                $r->setServer($realm);
                $r->save();
            }
            $actiont = 0;
            ksort($value);

            $this->doLogSection("Working", "Creating temporary cache for raid ".$raid."...");

            foreach ($value as $player => $data)
            {
                if ( isset($playerList[utf8_encode($player)]) )
                {
                    ksort($data["recentactions"]);
//                    ksort($data["recenthistory"]);
                    foreach ($data["recentactions"] as $actiontime => $ra)
                    {
                        if (!isset($recentactionsByPlayer[$actiontime]))
                            $recentactionsByPlayer[$actiontime] = array();
                        $recentactionsByPlayer[$actiontime][utf8_encode($player)] = $ra;
                    }
                    foreach ($data["recenthistory"] as $actiontime => $ra)
                    {
                        if ($actiontime > 100)
                        {
                            if (!isset($recentactionsByPlayer[$actiontime]))
                                $recentactionsByPlayer[$actiontime] = array();
                            $recentactionsByPlayer[$actiontime][utf8_encode($player)] = $ra;
                        }
                    }
                }
            }
            foreach ($recentactionsByPlayer as $actiontime => $data)
            {
//                if (count($data) == 1)
//                {
//                    foreach ($data as $player => $d)
//                    {
//                        if (!isset($raMisc[$player]))
//                            $raMisc[$player] = array();
//                        $raMisc[$player][$actiontime] = $d;
//                    }
//                }
//                else
//                {
                    $id = new DataImport();
                    $id->setText(
                        serialize(
                            array(
                                "playerList" => $playerList,
                                "raid" => $r->getId(),
                                "actiontime" => $actiontime,
                                "data" => $data
                            )
                        )
                    );
                    $id->setSize(count($data));
                    $id->save();
//                }
            }
//            if (count($raMisc) > 0)
//            {
//                $id = new DataImport();
//                $id->setText(
//                    serialize(
//                        array(
//                            "playerList" => $playerList,
//                            "raid" => $r->getId(),
//                            "actiontime" => $raMisc,
//                            "data" => $data
//                        )
//                    )
//                );
//                $id->setSize(count($data));
//                $id->save();
//            }
        }
    }

    $this->doLogSection("Working", "Starting background process...");
    $this->doLogSection("Working", sfConfig::get('sf_root_dir')."/symfony raidpoints:importRun' - ".sfConfig::get("app_path_to_php"));
    //system(sfConfig::get('sf_root_dir')."/symfony raidpoints:importRun");
	$bg = new BackgroundIt();
	$bg->run(sfConfig::get('sf_root_dir').'/symfony raidpoints:importRun', sfConfig::get("app_path_to_php"));	
    /*
    $r = Doctrine::getTable("History")->getLastLog('2009-07-05 17:01:59', 10, 1);
    $r = $r->getFirst();

    $r = Doctrine::getTable("PlayerHistory")->updatePoints(2, 1);

    $newHistory = new History();
    $newHistory->setDate('2009-07-05 17:01:59');
    $newHistory->setActiondate('2009-07-05 17:02:51');
    $newHistory->setSavedate($newHistory->getActiondate());
    $newHistory->setLogdate(time());
    $newHistory->setLogcomment(' ');
    $newHistory->setComment(' ');
    $newHistory->setItemid(0);
    $newHistory->setOfficerid(0);
    $newHistory->setPlayerid(10);
    $newHistory->setRaidid(1);
    $newHistory->setReasonid(831);
    $newHistory->setTtype('I');
    $newHistory->setValue('0');
    $newHistory->setWaitlistflag(0);
    $newHistory->setZoneid(0);
    $newHistory->setAaction("D");
    $newHistory->save();

    $this->logsection("do-nothing", "I did nothing...");
    //print_r($r->getAction());
    */


  }
}
